import tkinter as tk
from tkinter import ttk, messagebox


class HistoryViewer:
    """处理历史记录查看的类"""

    def __init__(self, app):
        self.app = app
        self.storage = app.storage
        self.colors = app.colors
        self.style = app.style

    def show_history_view(self):
        """显示历史记录视图"""
        # 清除现有界面
        for widget in self.app.winfo_children():
            widget.destroy()

        # 主框架
        history_frame = ttk.Frame(self.app, padding=20)
        history_frame.pack(fill=tk.BOTH, expand=True)

        # 返回按钮
        back_btn = ttk.Button(history_frame, text="返回", command=self.app.create_main_frame)
        back_btn.pack(anchor="nw", pady=(0, 10))

        # 标题
        title_label = ttk.Label(history_frame, text="历史打卡记录", style="Subheader.TLabel")
        title_label.pack(pady=(0, 20), anchor="w")

        # 筛选选项
        filter_frame = ttk.Frame(history_frame)
        filter_frame.pack(fill=tk.X, pady=10)

        # 按日期筛选（中文格式说明）
        ttk.Label(filter_frame, text="按日期筛选:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.date_var = tk.StringVar()
        date_entry = ttk.Entry(filter_frame, textvariable=self.date_var, width=12)
        date_entry.grid(row=0, column=1, padx=5, pady=5, sticky="w")
        ttk.Label(filter_frame, text="(年-月-日)").grid(row=0, column=2, padx=5, pady=5, sticky="w")

        date_btn = ttk.Button(
            filter_frame,
            text="筛选",
            command=lambda: self.filter_history_by_date(self.date_var.get())
        )
        date_btn.grid(row=0, column=3, padx=5, pady=5, sticky="w")

        # 按月份筛选（中文格式说明）
        ttk.Label(filter_frame, text="按月份筛选:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.month_var = tk.StringVar()
        month_entry = ttk.Entry(filter_frame, textvariable=self.month_var, width=10)
        month_entry.grid(row=1, column=1, padx=5, pady=5, sticky="w")
        ttk.Label(filter_frame, text="(年-月)").grid(row=1, column=2, padx=5, pady=5, sticky="w")

        month_btn = ttk.Button(
            filter_frame,
            text="筛选",
            command=lambda: self.filter_history_by_month(self.month_var.get())
        )
        month_btn.grid(row=1, column=3, padx=5, pady=5, sticky="w")

        # 删除按钮
        delete_btn = ttk.Button(
            filter_frame,
            text="删除选中记录",
            command=self.delete_selected_checkin,
            style="TButton"
        )
        self.style.configure("Delete.TButton", background=self.colors["danger"])
        delete_btn.configure(style="Delete.TButton")
        delete_btn.grid(row=1, column=4, padx=5, pady=5, sticky="w")

        # 历史记录列表
        self.history_listbox = tk.Listbox(history_frame, height=15, width=80, font=("Arial", 10))
        self.history_listbox.pack(fill=tk.BOTH, expand=True, pady=10)

        # 绑定双击事件查看详情
        self.history_listbox.bind("<Double-1>", self.show_checkin_detail)

        # 初始显示所有记录
        self.display_all_history()

    def delete_selected_checkin(self):
        """删除选中的打卡记录"""
        selection = self.history_listbox.curselection()
        if not selection:
            messagebox.showinfo("提示", "请先选择要删除的记录")
            return

        index = selection[0]
        log_text = self.history_listbox.get(index)

        # 跳过标题行和分隔线
        if log_text.startswith("未找到") or log_text.startswith("-") or log_text.startswith("暂无打卡记录"):
            return

        # 提取日期
        date_str = log_text.split()[0]

        # 查找对应的打卡记录
        log = next((l for l in self.app.checkins if l["date"] == date_str), None)
        if not log:
            messagebox.showerror("错误", "未找到该记录")
            return

        # 确认删除
        confirm = messagebox.askyesno("确认删除", f"确定要删除 {date_str} 的打卡记录吗?")
        if not confirm:
            return

        # 删除记录
        self.app.checkins = [l for l in self.app.checkins if l["date"] != date_str]
        self.storage.save_all_checkins_to_file(self.app.checkins)

        # 刷新显示
        self.display_all_history()

        # 显示成功消息
        messagebox.showinfo("成功", "记录已删除")

    def display_all_history(self):
        """显示所有历史记录"""
        self.history_listbox.delete(0, tk.END)
        if not self.app.checkins:
            self.history_listbox.insert(tk.END, "暂无打卡记录")
            return

        for log in sorted(self.app.checkins, key=lambda x: x["date"], reverse=True):
            mood_icon = self.storage.MOOD_ICONS[self.storage.PRESET_MOODS.index(log["mood"])]
            summary = log["study_summary"][:50] + ("..." if len(log["study_summary"]) > 50 else "")
            goal_info = ""

            if "goal_ids" in log:
                goal_names = []
                for goal_id in log["goal_ids"]:
                    goal = next((g for g in self.app.goals if g["goal_id"] == goal_id), None)
                    if goal:
                        goal_names.append(goal["description"])
                if goal_names:
                    goal_info = f" [关联目标: {', '.join(goal_names)}]"

            self.history_listbox.insert(tk.END, f"{log['date']} {mood_icon} {summary}{goal_info}")

    def filter_history_by_date(self, date_str):
        """按日期筛选历史记录"""
        if not date_str:
            messagebox.showerror("错误", "请输入日期")
            return

        filtered = [log for log in self.app.checkins if log["date"] == date_str]
        self.display_filtered_history(filtered, f"{date_str} 的打卡记录")

    def filter_history_by_month(self, month_str):
        """按月份筛选历史记录"""
        if not month_str:
            messagebox.showerror("错误", "请输入月份")
            return

        filtered = [log for log in self.app.checkins if log["date"].startswith(month_str)]
        self.display_filtered_history(filtered, f"{month_str} 的打卡记录")

    def display_filtered_history(self, logs, title):
        """显示筛选后的历史记录"""
        self.history_listbox.delete(0, tk.END)
        if not logs:
            self.history_listbox.insert(tk.END, f"未找到 {title}")
            return

        self.history_listbox.insert(tk.END, f"{title} ({len(logs)} 条记录)")
        self.history_listbox.insert(tk.END, "-" * 80)

        for log in sorted(logs, key=lambda x: x["date"], reverse=True):
            mood_icon = self.storage.MOOD_ICONS[self.storage.PRESET_MOODS.index(log["mood"])]
            summary = log["study_summary"][:50] + ("..." if len(log["study_summary"]) > 50 else "")
            goal_info = ""

            if "goal_ids" in log:
                goal_names = []
                for goal_id in log["goal_ids"]:
                    goal = next((g for g in self.app.goals if g["goal_id"] == goal_id), None)
                    if goal:
                        goal_names.append(goal["description"])
                if goal_names:
                    goal_info = f" [关联目标: {', '.join(goal_names)}]"

            self.history_listbox.insert(tk.END, f"{log['date']} {mood_icon} {summary}{goal_info}")

    def show_checkin_detail(self, event):
        """显示打卡详情"""
        selection = self.history_listbox.curselection()
        if not selection:
            return

        index = selection[0]
        log_text = self.history_listbox.get(index)

        # 跳过标题行和分隔线
        if log_text.startswith("未找到") or log_text.startswith("-"):
            return

        # 提取日期
        date_str = log_text.split()[0]

        # 查找对应的打卡记录
        log = next((l for l in self.app.checkins if l["date"] == date_str), None)
        if not log:
            return

        # 创建详情窗口
        detail_window = tk.Toplevel(self.app)
        detail_window.title(f"打卡详情 - {date_str}")
        detail_window.geometry("600x400")
        detail_window.resizable(True, True)

        # 详情框架
        detail_frame = ttk.Frame(detail_window, padding=20)
        detail_frame.pack(fill=tk.BOTH, expand=True)

        # 日期和时间
        ttk.Label(detail_frame, text=f"日期: {log['date']} {log['time']}",
                  font=("Arial", 12, "bold")).pack(anchor="w", pady=(0, 10))

        # 心情
        mood_icon = self.storage.MOOD_ICONS[self.storage.PRESET_MOODS.index(log["mood"])]
        ttk.Label(detail_frame, text=f"心情: {mood_icon} {log['mood']}",
                  font=("Arial", 11)).pack(anchor="w", pady=(0, 5))

        # 学习小结
        ttk.Label(detail_frame, text="学习小结:", font=("Arial", 11, "bold")).pack(anchor="w", pady=(10, 2))
        summary_text = tk.Text(detail_frame, height=5, wrap=tk.WORD, font=("Arial", 10))
        summary_text.insert(tk.END, log["study_summary"])
        summary_text.config(state=tk.DISABLED)
        summary_text.pack(fill=tk.BOTH, expand=True, pady=(0, 10))

        # 生活感悟
        if log.get("life_notes"):
            ttk.Label(detail_frame, text="生活感悟:", font=("Arial", 11, "bold")).pack(anchor="w", pady=(10, 2))
            notes_text = tk.Text(detail_frame, height=3, wrap=tk.WORD, font=("Arial", 10))
            notes_text.insert(tk.END, log["life_notes"])
            notes_text.config(state=tk.DISABLED)
            notes_text.pack(fill=tk.BOTH, expand=True, pady=(0, 10))

        # 关联目标
        if "goal_ids" in log:
            goal_names = []
            for goal_id in log["goal_ids"]:
                goal = next((g for g in self.app.goals if g["goal_id"] == goal_id), None)
                if goal:
                    goal_names.append(f"{goal['description']} [{goal['status']}]")

            if goal_names:
                ttk.Label(detail_frame, text="关联目标:", font=("Arial", 11, "bold")).pack(anchor="w", pady=(10, 2))
                goals_text = tk.Text(detail_frame, height=2, wrap=tk.WORD, font=("Arial", 10))
                goals_text.insert(tk.END, "\n".join(goal_names))
                goals_text.config(state=tk.DISABLED)
                goals_text.pack(fill=tk.BOTH, expand=True, pady=(0, 10))